﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AteneoLibriBusinessLogic.Entities;
using AteneoLibriBusinessLogic.MyException;

namespace AteneoLibriBusinessLogic.DAL
{
    public class MessageFacade
    {

        AteneoLibriEntityFramework.AteneoLibriEntities db = new AteneoLibriEntityFramework.AteneoLibriEntities();

        public List<Message> getMessagesBetweenSellerPurchaser(Guid sellerId, Guid purchaserId)
        {
            List<Message> messages = new List<Message>();
            List<AteneoLibriEntityFramework.Message> listMessages = db.Messages.Where(x => x.UserIdSeller == sellerId && x.UserIdPurchaser == purchaserId).ToList();

            foreach (var item in listMessages)
            {
                Message msg = TOA.MessageAssembler.Assembler(item);
                messages.Add(msg);
            }

            return messages;
        }

        public bool insertMessage(Message message)
        {
            bool result = false;
            try
            {
                AteneoLibriEntityFramework.Message messageEF = TOA.MessageAssembler.DeAssembler(message);
                db.Messages.AddObject(messageEF);
                db.SaveChanges();

                result = true;
            }
            catch (Exception ex)
            {
                throw new DALException(ex.Message, ex);
            }

            return result;
        }

        public bool deleteMessages(Guid userId)
        {
            bool result = false;
            try
            {
                List<AteneoLibriEntityFramework.Message> messages = db.Messages.Where(x => x.UserIdSeller == userId || x.UserIdPurchaser == userId || x.WriteBy == userId).ToList();

                foreach (var item in messages)
                {
                    db.Messages.DeleteObject(item);
                }
                db.SaveChanges();

                result = true;
            }
            catch (Exception ex)
            {
                result = false;
            }

            return result;
        }
    }
}
